
let layerIndex;
/**
 * 弹出学生新增/更新对话框
 */
function showTeacherDlg(id){
    let title="新增老师"
    if(id){
        title="编辑老师"
        $("#formId").css("display", "block");

        $.ajax({
            url: "/api/teacher/"+id,
            method:"GET"
        }).done(result=>{
            console.log(result)

        $.each(result,function(key, value) {

                var field = $('#teaForm [name="' + key + '"]');
                if (field.is( ':radio')) {
                    field.filter('[value="'+ value + '"]').prop('checked', true);
                }else if(field.is(':checkbox')){
                    field.prop('checked', value === "yes");
                }else {
                    field.val(value);
                }
            });

        })


    }else{
        $("#teaForm")[0].reset();
        $("#formId").css("display", "none");

    }

    layerIndex=layer.open({
        type: 1,
        title:title,
        area: ['520px', 'auto'],
            content: $('#teaForm')
    });

}
function getSearchCondtion() {
    let formData = {}
//遍历每个输入元素，将其值存储到 formData 对象中
    $('#queryForm').find('input, select').each(function () {
        let name = $(this).attr('name'); //获取元素的name属性
        let value = $(this).val(); // 获取元素的值
//只有 name属性存在且值不为空才会添加到 formData 中
        if (name && value) {
            formData[name] = value;
        }
    });
    return formData
}



layui.use(function() {
    layui.form.on('submit(tea-dlg)', function (data) {
        event.preventDefault();
        commitTeaDlg();
    })

    const table = layui.table;
    let teacher = getSearchCondtion();

    table.render({
        elem: '#tbTeacher',
        url: '/api/teacher/getbypage', //此处为静态模拟数据，实际使用时需换成真实接口
        method: "POST",
        contentType: 'application/json', // 确保以 JSON 格式发送
        where: {"data": teacher},
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', fixed: 'left', width: 80, title: 'id', sort: true},
            {field: 'name', title: '姓名'},
            {
                field: 'sno',
                title: '学号',
                width: 150,
            },
            {
                field: 'sex', width: 80, title: '性别', sort: true,
                templet: d => d.sex === 1 ? '男' : (d.sex === 2 ? '女' : '未知'),
            },
            {field: ' age', width: 100, title: '年龄', sort: true},
            {fixed: ' right', title: '操作', width: 134, minWidth: 125, templet: '#editTemplate'}
        ]],
        done: function (rs) {
// console. log(rs)
        }
    });

    function commitTeaDlg() {
        let id = $("#id").val()
        let formData = $("#teaForm").serialize();
        if (id != null && id != "") {
            $.ajax({
                url: "/api/teacher/update",
                method: "PUT",
                data: formData
            }).done(result => {
                console.log(result);
                if (result.id) {

                    loadTeacherList();
                    console.log(" add success!")
                    if (layerIndex)
                        layer.close(layerIndex)
                    loadTeacherList();
                }
            }).fail((jqXHR, textStatus, errorThrown) => {
                console.error(" Request failed: " + textStatus + " - " + errorThrown);

                alert(" An error occurred. Please try again. ");
            });

        } else {

            $.ajax({
                url: "/api/teacher/add",
                method: "POST",
                data: formData
            }).done(result => {
                console.log(result);
                if (result.id) {

                    loadTeacherList();
                    console.log(" add success!")
                    if (layerIndex)
                        layer.close(layerIndex)
                    loadTeacherList();
                }
            }).fail((jqXHR, textStatus, errorThrown) => {
                console.error(" Request failed: " + textStatus + " - " + errorThrown);

                alert(" An error occurred. Please try again. ");
            });

        }

        $("#btn0K").prop(" disabled", true).addClass("layui-btn-disabled"); // 禁用按钮
    }

    function deleteById(id) {
        layer.confirm('你真的要删除吗？一旦删除，不可恢复！', {icon: 3}, function () {

            $.ajax({
                url: "/api/teacher/delete/" + id,
                method: "DELETE",
            }).done(result => {
                loadTeacherList();

            })
            layer.closeAll();

        }, function () {

        });
    }})
